package com.wang.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import com.wang.springframework.beans.BeansException;
import com.wang.springframework.beans.PropertyValue;
import com.wang.springframework.beans.PropertyValues;
import com.wang.springframework.beans.factory.config.AutowireCapableBeanFactory;
import com.wang.springframework.beans.factory.config.BeanDefinition;
import com.wang.springframework.beans.factory.config.BeanPostProcessor;
import com.wang.springframework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;

/**
 * @author wangjianhua
 * @Description
 * @date 2021/8/25/025 14:32
 **/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {

    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();


    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try
        {
            bean = createBeanInstance(beanDefinition, beanName, args);
            //填充属性
            applyPropertyValues(beanName,bean,beanDefinition);
            //执行bean的初始化方法 和BeanPostProcessor 的前置与后置处理方法
            bean = initializeBean(beanName,bean,beanDefinition);
        }
        catch (Exception e)
        {
            throw new BeansException("Instantiate of bean failed",e);
        }
        addSingleton(beanName,bean);
        return bean;
    }


    protected Object createBeanInstance(BeanDefinition beanDefinition,String beanName,Object[] args){
        Constructor<?> constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor<?> ctor : declaredConstructors) {
            if(null != args && ctor.getParameterTypes().length == args.length){
                constructorToUse = ctor;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanDefinition,beanName,constructorToUse,args);
    }

    /**
     * bean属性填充
     */
    protected void applyPropertyValues(String beanName,Object bean,BeanDefinition beanDefinition){
        try
        {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {

                String name = propertyValue.getName();
                Object value = propertyValue.getValue();

                if(value instanceof BeanReference){
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }

                BeanUtil.setFieldValue(bean,name,value);
            }
        }
        catch (Exception e)
        {
            throw new BeansException("Error setting property values"+beanName);
        }
    }




    /**
     * 初始化bean
     * @param beanName beanName
     * @param bean bean
     * @param beanDefinition beanDefinition
     * @return bean
     */
    private Object initializeBean(String beanName,Object bean,BeanDefinition beanDefinition){
        //1. 执行 BeanPostProcessor Before处理

        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);

        // 待完成内容:invokeInitMethods
        invokeInitMethods(beanName, wrappedBean, beanDefinition);

        //2. 执行 BeanPostProcessor After处理
        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean,beanName);
        return wrappedBean;
    }

    private void invokeInitMethods(String beanName,Object wrappedBean,BeanDefinition beanDefinition){

    }

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessorAfterInitialization(result, beanName);
            if(null == current){
                return result;
            }
            result = current;
        }
        return result;
    }

    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessorBeforeInitialization(result, beanName);
            if(null == current){
                return result;
            }
            result = current;
        }
        return result;
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
